﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;

namespace PASNew.U.Controls
{
	public partial class Clients : System.Web.UI.UserControl
	{
		

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			AsyncFileUpload1.UploadedComplete +=new EventHandler<AjaxControlToolkit.AsyncFileUploadEventArgs>(AsyncFileUpload1_UploadedComplete);
			
		}

		private void AsyncFileUpload1_UploadedComplete(object sender, AjaxControlToolkit.AsyncFileUploadEventArgs e)
		{
			System.Threading.Thread.Sleep(5000);
			if (AsyncFileUpload1.HasFile)
			{
				string strPath = MapPath("../../Uploads/PAS/") + Path.GetFileName(e.FileName);
				AsyncFileUpload1.SaveAs(strPath);
			}
		}

		private void ClearControls()
		{
			txtBoxCompanyName.Text = string.Empty;
			txtBoxContactName.Text = string.Empty;
			txtBoxEmail.Text = string.Empty;
			txtBoxCellphone.Text = string.Empty;
			txtBoxPhysical.Text = string.Empty;
			txtBoxWebsite.Text = string.Empty;
			//DPChange.SelectedDates.Clear();
			//DPEndDate.SelectedDates.Clear();
			txtBoxAmount.Text = string.Empty;
			txtBoxNotes.Text = string.Empty;
			lblSuccess.Visible = false;
			txtBoxLandline.Text = string.Empty;
		}

		public string makeCamel(string original)
		{
			if (string.IsNullOrEmpty(original)) return string.Empty;
			// convert to char array of the string    
			char[] letters = original.ToCharArray();
			// upper case the first char    
			letters[0] = char.ToUpper(letters[0]);
			// return the array made of the new char array    
			return new string(letters);
		}

		public void AdvertisedYes()
		{
			lblChange.Text = "Start Date";

			lblChange.Visible = true;
			lblEndDate.Visible = true;
			lblAmount.Visible = true;
			//DPChange.Visible = true;
			//DPEndDate.Visible = true;
			txtBoxAmount.Visible = true;


		}

		public void AdvertisedNo()
		{
			lblChange.Text = "Contact Again";

			lblChange.Visible = true;
			lblEndDate.Visible = false;
			lblAmount.Visible = false;
			//DPChange.Visible = true;
			//DPEndDate.Visible = false;
			txtBoxAmount.Visible = false;

		}

		protected void Page_Load(object sender, EventArgs e)
		{
			//#region used for date pickers
			//Boxesdto Boxcheck = (Boxesdto)Session["BoxCheck"];
			//Boxes2dto Boxcheck2 = (Boxes2dto)Session["BoxCheck2"];

			//if (Session["BoxCheck"] != null)
			//{
			//    if (Boxcheck.Box == 1)
			//    {
			//        dpChangeUC.Visible = true;
			//    }
			//    else
			//    {
			//        dpChangeUC.Visible = false;
			//    }
			//}

			//if (Session["BoxCheck2"] != null)
			//{
			//    if (Boxcheck2.Box2 == 1)
			//    {
			//        dpEndDateUC.Visible = true;
			//    }
			//    else
			//    {
			//        dpEndDateUC.Visible = false;
			//    }
			//}
			//#endregion

			//DDClientLoad.SelectedIndexChanged += new EventHandler(DDClientLoad_SelectedIndexChanged);

			//if (Session["Delete"] != null)// reloads the page and lets the user know they deleted the user
			//{
			//    lblSuccess.Text = "Client successfully deleted";
			//    lblSuccess.Visible = true;
			//}

			////if (Session["UserIdentity"] != null)
			////{
			//    if (!IsPostBack)
			//    {
			//       // UserDetailsDto user = (UserDetailsDto)Session["UserIdentity"];
			//        UserDetailsDto user = new UserDetailsDto
			//        {
			//             UserID = 1,
			//        };

			//        using (PASDataDataContext data = new PASDataDataContext())
			//        {
			//            var load = from s in data.ClientUserRelations
			//                       where s.UserId == user.UserID
			//                       from cl in data.ClientDetails
			//                       where cl.ClientId == s.ClientId
			//                       orderby cl.CompanyName
			//                       select new ListItem
			//                       {
			//                           Text = cl.CompanyName,
			//                           Value = cl.ClientId.ToString(),
			//                       };

			//            DDClientLoad.DataSource = load;
			//            DDClientLoad.DataBind();


			//            ///Its better if I just explain in chat or person

			//            if (Session["LoadedCompanyName"] != null)
			//            {
			//                NotificationsDto cID = (NotificationsDto)Session["LoadedCompanyName"];

			//                var NotificationsLoad = (from t in data.ClientDetails
			//                                         where t.CompanyName == cID.ClientCompName
			//                                         select t).FirstOrDefault();
			//                if (NotificationsLoad != null)
			//                {
			//                    txtBoxCompanyName.Text = NotificationsLoad.CompanyName == null ? string.Empty : NotificationsLoad.CompanyName.ToString();
			//                    txtBoxContactName.Text = NotificationsLoad.ContactName == null ? string.Empty : NotificationsLoad.ContactName.ToString();
			//                    txtBoxEmail.Text = NotificationsLoad.ClientEmail == null ? string.Empty : NotificationsLoad.ClientEmail.ToString();
			//                    txtBoxCellphone.Text = NotificationsLoad.CellphoneNumber == null ? string.Empty : NotificationsLoad.CellphoneNumber.ToString();
			//                    txtBoxLandline.Text = NotificationsLoad.LandlineNumber == null ? string.Empty : NotificationsLoad.LandlineNumber.ToString();
			//                    txtBoxPhysical.Text = NotificationsLoad.Address == null ? string.Empty : NotificationsLoad.Address.ToString();
			//                    txtBoxWebsite.Text = NotificationsLoad.Website == null ? string.Empty : NotificationsLoad.Website.ToString();
			//                    txtBoxNotes.Text = NotificationsLoad.Notes == null ? string.Empty : NotificationsLoad.Notes.ToString();

			//                    if (NotificationsLoad.Advertised == 1)
			//                    {
			//                        AdvertiseCheck.SelectedIndex = 0;
			//                        AdvertisedYes();

			//                        //DPChange.SelectedDate = Convert.ToDateTime(NotificationsLoad.StartDate);
			//                        //DPEndDate.SelectedDate = Convert.ToDateTime(NotificationsLoad.EndDate);
			//                        txtBoxAmount.Text = NotificationsLoad.Amount == null ? string.Empty : NotificationsLoad.Amount.ToString();
			//                    }

			//                    if (NotificationsLoad.Advertised == 2)
			//                    {
			//                        AdvertiseCheck.SelectedIndex = 1;
			//                        AdvertisedNo();

			//                        //DPChange.SelectedDate = Convert.ToDateTime(NotificationsLoad.ContactAgain);
			//                    }
			//                }
			//            }
			//        }
			//    }
			////}
			////else
			////{
			////    Response.Redirect("Home.aspx");
			////}
		}

		protected void DDClientLoad_SelectedIndexChanged(object sender, EventArgs e)
		{
			lblSuccess.Visible = false;

			lblChange.Visible = false;
			lblEndDate.Visible = false;
			lblAmount.Visible = false;
			//DPChange.Visible = false;
			//DPEndDate.Visible = false;
			txtBoxAmount.Visible = false;


			using (PASDataDataContext data = new PASDataDataContext())
			{
				var s = (from c in data.ClientDetails
						 where c.CompanyName == DDClientLoad.Text
						 select c).FirstOrDefault();

				txtBoxCompanyName.Text = s.CompanyName == null ? string.Empty : s.CompanyName.ToString();
				txtBoxContactName.Text = s.ContactName == null ? string.Empty : s.ContactName.ToString();
				txtBoxEmail.Text = s.ClientEmail == null ? string.Empty : s.ClientEmail.ToString();
				txtBoxLandline.Text = s.LandlineNumber == null ? string.Empty : s.LandlineNumber.ToString();
				txtBoxCellphone.Text = s.CellphoneNumber == null ? string.Empty : s.CellphoneNumber.ToString();
				txtBoxPhysical.Text = s.Address == null ? string.Empty : s.Address.ToString();
				txtBoxWebsite.Text = s.Website == null ? string.Empty : s.Website.ToString();
				txtBoxNotes.Text = s.Notes == null ? string.Empty : s.Notes.ToString();

				if (s.Advertised == 1)//did advertise
				{

					//DPChange.SelectedDate = Convert.ToDateTime(s.StartDate);
					//DPEndDate.SelectedDate = Convert.ToDateTime(s.EndDate);
					txtBoxAmount.Text = s.Amount == null ? string.Empty : s.Amount.ToString();

					AdvertisedYes();
				}

				if (s.Advertised == 2) //didnt advertise
				{

					//DPChange.SelectedDate = Convert.ToDateTime(s.ContactAgain);

					AdvertisedNo();
				}
			}
			DDClientLoad.SelectedIndex = 0;
		}

		protected void btnNew_Click(object sender, EventArgs e)
		{
			ClearControls();
			Session["LoadedCompanyName"] = null;
			Response.Redirect("Clients.aspx");
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			string CompanyNameNEW = makeCamel(txtBoxCompanyName.Text);

			UserDetailsDto user = (UserDetailsDto)Session["UserIdentity"];
			CompIDdto company = (CompIDdto)Session["CompanyIdentitifier"];

			using (PASDataDataContext data = new PASDataDataContext())
			{
				var checkifexists = (from a in data.ClientDetails
									 where a.CompanyName == CompanyNameNEW
									 select a).FirstOrDefault();

				if (checkifexists != null)
				{
					var ucr = (from r in data.ClientUserRelations
							   where r.ClientId == checkifexists.ClientId
							   select r).FirstOrDefault();

					if (ucr != null && ucr.UserId != user.UserID)
					{
						var wii = (from w in data.UserDetails
								   where w.UserId == ucr.UserId
								   select w).FirstOrDefault();

						lblSuccess.Visible = true;
						lblSuccess.Text = "Client already exists! Client managed by: " + wii.UserName.ToString();
					}
					else
					{
						#region update client if the user

						var update = (from db in data.ClientDetails
									  where db.ClientId == checkifexists.ClientId
									  select db).Single();

						update.CompanyName = makeCamel(txtBoxCompanyName.Text);
						update.ContactName = makeCamel(txtBoxContactName.Text);
						update.ClientEmail = makeCamel(txtBoxEmail.Text);
						update.CellphoneNumber = txtBoxCellphone.Text.ToString();
						update.LandlineNumber = txtBoxLandline.Text.ToString();
						update.Address = makeCamel(txtBoxPhysical.Text);
						update.Website = txtBoxWebsite.Text.ToString();
						update.Notes = makeCamel(txtBoxNotes.Text);
						//update.ClientId = update.ClientId;


						//if (AdvertiseCheck.SelectedIndex == 0)
						//{
						//    update.Advertised = 1;
						//    //update.StartDate = //DPChange.SelectedDate;
						//    //update.EndDate = //DPEndDate.SelectedDate;
						//    update.Amount = txtBoxAmount.ToString();
						//}
						//else if (AdvertiseCheck.SelectedIndex == 1)
						//{
						//    update.Advertised = 2;
						//    //update.ContactAgain = //DPChange.SelectedDate;
						//}
						//else
						//{
						//    update.Advertised = 3;
						//}

						data.SubmitChanges();

						#endregion //needs to be checked
						lblSuccess.Text = "Client successfully updated";
						lblSuccess.Visible = true;
					}
				}
				else
				{
					#region save client to clientdetails
					ClientDetail newUser = new ClientDetail();

					newUser.CompanyName = makeCamel(txtBoxCompanyName.Text);
					newUser.ContactName = makeCamel(txtBoxContactName.Text);
					newUser.ClientEmail = makeCamel(txtBoxEmail.Text);
					newUser.CellphoneNumber = txtBoxCellphone.Text.ToString();
					newUser.LandlineNumber = txtBoxLandline.Text.ToString();
					newUser.Address = makeCamel(txtBoxPhysical.Text);
					newUser.Website = txtBoxWebsite.Text.ToString();
					newUser.Notes = makeCamel(txtBoxNotes.Text);

					//if (AdvertiseCheck.SelectedIndex == 0)
					//{
					//    newUser.Advertised = 1;
					//    //newUser.StartDate = DPChange.SelectedDate;
					//    //newUser.EndDate = DPEndDate.SelectedDate;
					//    newUser.Amount = txtBoxAmount.Text.ToString();
					//}
					//else if (AdvertiseCheck.SelectedIndex == 1)
					//{
					//    newUser.Advertised = 2;
					//    //newUser.ContactAgain = DPChange.SelectedDate;
					//}
					//else
					//{
					//    newUser.Advertised = 3;
					//}

					data.ClientDetails.InsertOnSubmit(newUser);
					data.SubmitChanges();

					#endregion

					var loadsavedclient = (from lsc in data.ClientDetails
										   where lsc.CompanyName == makeCamel(txtBoxCompanyName.Text)
										   select lsc).FirstOrDefault();

					#region save the relationship between client and user

					ClientUserRelation newRelationship = new ClientUserRelation();

					newRelationship.ClientId = loadsavedclient.ClientId;
					newRelationship.UserId = user.UserID;
					data.ClientUserRelations.InsertOnSubmit(newRelationship);

					data.SubmitChanges();

					#endregion
					lblSuccess.Text = "Client successfully saved";
					lblSuccess.Visible = true;

					DDClientLoad.Items.Add(makeCamel(txtBoxCompanyName.Text.ToString()));//ads the saved item to the drop down list
				}
			}
		}

		protected void btnDelete_Click(object sender, EventArgs e)
		{
			using (PASDataDataContext data = new PASDataDataContext())
			{
				var x = (from c in data.ClientDetails
						 where c.CompanyName.ToLower() == makeCamel(txtBoxCompanyName.Text)
						 select c).FirstOrDefault();

				data.ClientDetails.DeleteOnSubmit(x);

				var z = (from y in data.ClientUserRelations
						 where y.ClientId == x.ClientId
						 select y).FirstOrDefault();

				data.ClientUserRelations.DeleteOnSubmit(z);
				data.SubmitChanges();
			}
			Session["LoadCompany"] = null;
			Session["Delete"] = 1;
			Response.Redirect("Clients.aspx");
		}

		protected void AdvertiseCheck_SelectedIndexChanged(object sender, EventArgs e)
		{
			lblSuccess.Visible = false;

			//if (AdvertiseCheck.SelectedIndex == 0)
			//{
			//    AdvertisedYes();
			//}
			//else
			//{
			//    AdvertisedNo();
			//}
		}

		protected void btnUpload_Click(object sender, EventArgs e)
		{
			//if (FileUpload1.HasFile != null)//wtf idiot? a bool can never be null whahahahaha its like trying to devide by zero
			//{
			//    //Server.MapPath("~/Images/Logos/" + uploadedFileName);

			//    //FileUpload1.PostedFile.SaveAs(Server.MapPath(" ")+"\\YourImageDirectoryOnServer\\"+FileUpload1.FileName);
			//}
		}
	}
}